from helpers import updateInfo
import datetime
import os
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class MainPage(webapp.RequestHandler):
    """ Statistics page class """
    def get(self):
        user=users.get_current_user()
        
        # Make sure user is logged in, if not redirect to login page
        if not user:
            self.redirect(users.create_login_url(self.request.uri))
            return
            
        # Load user info from database
        # If user is using app for first time (=his info in not in TrendUsers table)
        # then initialize his info
        current_user=updateInfo.getCurrentUser(user)
    
        q_1 = db.GqlQuery("SELECT * FROM StocksData ORDER BY precentChange DESC LIMIT 0,3")
        results=q_1.fetch(5)
        
        q_2 = db.GqlQuery("SELECT * FROM StocksData ORDER BY precentChange ASC")
        results2=q_2.fetch(5)
        results2.reverse()
        
        YesterdayStockExchange="data.addRows(%d);\n" % (len(results)+len(results2))
        i=0
        for stock in results:
            printPercentage, fontColor, changeSign= updateInfo.getPerInfo(stock.precentChange)
            if (stock.precentChange<1):
                printPercentage=printPercentage*(-1)
    
            YesterdayStockExchange+="data.setValue(%d, 0, '%s', '%s');\n" % (i,stock.stockname,stock.stockname)
            YesterdayStockExchange+="data.setValue(%d, 1, %.2f);\n" % (i,printPercentage)
            i=i+1
    
        for stock in results2:
            printPercentage, fontColor, changeSign= updateInfo.getPerInfo(stock.precentChange)
            if (stock.precentChange<1):
                printPercentage=printPercentage*(-1)
                
            YesterdayStockExchange+="data.setValue(%d, 0, '%s');\n" % (i,stock.stockname)
            YesterdayStockExchange+="data.setValue(%d, 1, %.2f);\n" % (i,printPercentage)
            i=i+1
    
            
        # Updating most-beneficial-trend: the trend that made the biggest increase for the long run
        q_4 = db.GqlQuery("SELECT * FROM Stocks ORDER BY userPrecentChange DESC")
        if q_4.count >0:
            StockList = []
            StockListNames = []
            counter=0
            for stock in q_4:
                if stock.stockref==None:
                    continue
                # Legendary before Yahoo
                #if stock.buydate.strftime("%Y-%m-%d")==datetime.datetime.now().strftime("%Y-%m-%d"):
                    #continue
                if StockListNames.count(stock.stockref.stockname)==0:
                    StockList.append(stock)
                    StockListNames.append(stock.stockref.stockname)
                    counter=counter+1
                if counter==5:
                    break
        
        # Updating table
        mostBeneficialTrendTable="\ndata2.addRows(%d);\n" % len(StockList)
        i=0
        for stock in StockList:
            if stock.stockref!=None:
                stocknameLink='<a href="/trendProfile?TKey=%s" style="color:#3366CC">%s</a>' % (str(stock.stockref.key()),stock.stockref.stockname)
            else:
                stocknameLink='%s' % stock.stockref.stockname
            
            buyDate=stock.buydate.strftime("%Y-%m-%d")
            printPercentage, fontColor, changeSign= updateInfo.getPerInfo(stock.userPrecentChange)
            mostBeneficialTrendTable+="data2.setCell(%d, 0, '%s');\n" % (i, stocknameLink)
            mostBeneficialTrendTable+="data2.setCell(%d, 1, %s,'%s');\n" % (i,buyDate.replace('-',''), buyDate)
            mostBeneficialTrendTable+="data2.setCell(%d, 2, %.2f,'(%s%.2f)',{style: 'color:%s;'});\n" % (i,stock.userPrecentChange, changeSign,printPercentage,fontColor)
            mostBeneficialTrendTable+="data2.setCell(%d, 3, '%s');\n" % (i, stock.buyer)
            i=i+1
    
    
        q_popular= db.GqlQuery("SELECT * FROM StocksData ORDER BY stockcounter DESC LIMIT 0,20")
        q_popular=q_popular.fetch(12)
        PopularTrendTable="\ndata4.addRows(%d);\n" % len(q_popular)
        i=0
        for stock in q_popular:
            PopularTrendTable+="data4.setValue(%d, 0, '%s');\n" % (i, stock.stockname)
            PopularTrendTable+="data4.setValue(%d, 1, %d);\n" % (i,stock.stockcounter)
            i=i+1
            
        
        template_values = {
            'YesterdayStockExchange': YesterdayStockExchange,
            'PopularTrendTable' : PopularTrendTable,
            'mostBeneficialTrendTable' : mostBeneficialTrendTable,
            'logusername' : user.nickname().capitalize(),
            'loginurl' : users.create_logout_url("/"),
            'current_user_totalamount': current_user.totalamount,
            'current_user_bankamount': current_user.bankamount,
            'current_user_investamount': current_user.totalamount-current_user.bankamount,
            'logintext' : 'Sign Out',
            'categoryName' : 'Statistics %s' % updateInfo.createToolTip("statistics"),
            'setHead' : 1,
            'maincontent' : 'account_main.html',
            'headContent' : 'stat_head.html',
            'account_main_content' : 'stat_main.html'
            
        }
        path = os.path.join(os.path.dirname(__file__), updateInfo.controllersIndexPath)
        self.response.out.write(template.render(path, template_values))
        

application = webapp.WSGIApplication(
                                     [('/statistics', MainPage)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
